# -*- encoding: utf-8 -*-


import time
import mod.server.extraServerApi as serverApi
import lobbyGame.netgameApi as lobbyGameApi
import nuoyanlib_server as nyl
from nuoyanlib_server import CompFactory, LvComp
from .common.constants import *
from .common.lang import *
from mySqlManager import MySqlManager
from hackerBuyer import HackerBuyer


EffectTypeEnum = serverApi.GetMinecraftEnum().EffectType


ALL_EFFECTS = {
    EffectTypeEnum.MOVEMENT_SPEED: 4,
    EffectTypeEnum.JUMP: 4,
    EffectTypeEnum.DAMAGE_BOOST: 4,
    EffectTypeEnum.DAMAGE_RESISTANCE: 1,
}


class HackerServerSystem(nyl.NuoyanServerSystem):
    def __init__(self, namespace, systemName):
        super(HackerServerSystem, self).__init__(namespace, systemName)
        self.hackerBuyer = HackerBuyer(namespace, systemName, self)
        self.__opening_players = []

    def Destroy(self):
        super(HackerServerSystem, self).Destroy()
        del self.__opening_players
        self.hackerBuyer.Destroy()

    # ------------------------------------------------------------------------------------------------------------------
    # Listener

    def CommandEvent(self, event_data):
        entityId = event_data['entityId']
        command = event_data['command']
        if command == "/t31 2b2t hacker open":
            self.TryOpenPlayerHacker(entityId)
        elif command == "/t31 2b2t hacker close":
            self.TryClosePlayerHacker(entityId)

    def PlayerIntendLeaveServerEvent(self, args):
        # 关闭科学家功能
        playerId = args['playerId']
        self.__opening_players.remove(playerId)
        self.RemoveAllEffects(playerId)

    @nyl.event(namespace=MOD_NAME, system_name=HACKER_SERVER_NAME)
    def CheckHackerResultEvent(self, args):
        """
        调用HackerBuyer.CheckHacker后会触发此事件，返回查询结果。
        参数：
            uid: int, 玩家uid
            has_buy: bool, 是否购买商品
        """

    def OnOpenBtnTouchUp(self, args):
        """
        开关按钮。
        """
        playerId = args['__id__']
        self.TrySwitchHackerUI(playerId)

    def OnPowerBtnTouchUp(self, args):
        """
        力量按钮。
        """
        playerId = args['__id__']
        self.SwitchEffect(playerId, EffectTypeEnum.DAMAGE_BOOST)

    def OnSpeedBtnTouchUp(self, args):
        """
        加速按钮。
        """
        playerId = args['__id__']
        self.SwitchEffect(playerId, EffectTypeEnum.MOVEMENT_SPEED)

    def OnKxtsBtnTouchUp(self, args):
        """
        抗性提升按钮。
        """
        playerId = args['__id__']
        self.SwitchEffect(playerId, EffectTypeEnum.DAMAGE_RESISTANCE)

    def OnJumpBtnTouchUp(self, args):
        """
        高跳按钮。
        """
        playerId = args['__id__']
        self.SwitchEffect(playerId, EffectTypeEnum.JUMP)

    # ------------------------------------------------------------------------------------------------------------------
    # Development

    def OpenPlayerHacker(self, playerId):
        self.NotifyToClient(playerId, EVENT_REQUEST_OPEN_HACKER_UI, {'ui_json': hacker_ui})
        self.__opening_players.append(playerId)

    def ClosePlayerHacker(self, playerId):
        self.NotifyToClient(playerId, EVENT_REQUEST_CLOSE_HACKER_UI, {})
        self.RemoveAllEffects(playerId)
        self.__opening_players.remove(playerId)

    def SendMsg(self, playerId, langStr):
        msg = LANG_STR_MAPPING[langStr]
        CompFactory.CreateMsg(playerId).NotifyOneMessage(playerId, msg)

    # ------------------------------------------------------------------------------------------------------------------
    # Interface

    def QueryPlayerHackerDeadline(self, uid, callback):
        """
        查询玩家的科学家过期时间并且将过期时间[int]作为callback的唯一参数
        """
        return MySqlManager.QueryPlayerHackerDeadline(uid, callback)

    def AddPlayerHackerTime(self, uid, addition=1):
        """
        增加玩家科学家过期时间
        """
        return MySqlManager.AddPlayerHackerTime(uid, addition * 2592000)

    def TryOpenPlayerHacker(self, playerId):
        """
        尝试打开某个玩家的科学家UI
        """
        def callback(deadline):
            print "TryOpenPlayerHacker: %s" % deadline, type(deadline)
            ct = time.time()
            if deadline == 0 or deadline > ct:
                self.OpenPlayerHacker(playerId)
                self.SendMsg(playerId, "t31.2b2t.hacker.open.success")
                print "科学家剩余时间：%d天" % ((deadline - ct) / 86400)
            else:
                self.SendMsg(playerId, "t31.2b2t.hacker.open.fail.not-own")
        if playerId in self.__opening_players:
            self.SendMsg(playerId, "t31.2b2t.hacker.open.fail.already")
        else:
            uid = lobbyGameApi.GetPlayerUid(playerId)
            self.QueryPlayerHackerDeadline(uid, callback)

    def TryClosePlayerHacker(self, playerId):
        """
        尝试关闭某个玩家的科学家UI
        """
        if playerId in self.__opening_players:
            self.ClosePlayerHacker(playerId)
            self.SendMsg(playerId, "t31.2b2t.hacker.close.success")
        else:
            self.SendMsg(playerId, "t31.2b2t.hacker.close.fail.not-open")

    def TrySwitchHackerUI(self, playerId):
        """
        尝试切换某个玩家的科学家UI的开关状态
        """
        if playerId in self.__opening_players:
            self.TryClosePlayerHacker(playerId)
        else:
            self.TryOpenPlayerHacker(playerId)

    def SwitchEffect(self, playerId, effect):
        effComp = CompFactory.CreateEffect(playerId)
        if playerId in self.__opening_players and not effComp.HasEffect(effect):
            effComp.AddEffectToEntity(effect, 99999, ALL_EFFECTS[effect], False)
        else:
            effComp.RemoveEffectFromEntity(effect)

    def RemoveAllEffects(self, playerId):
        for i in ALL_EFFECTS:
            CompFactory.CreateEffect(playerId).RemoveEffectFromEntity(i)















